//    Copyright (C) 2013  <lugocreation@gmail.com>
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
package org.jpgolay.me.piece.list;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyVetoException;
import javax.swing.*;
import org.jpgolay.gui.date.DateComboBox;
import org.jpgolay.gui.fixed.*;
import org.jpgolay.me.util.MEDate;
import org.jpgolay.me.util.MEUtility;

// Referenced classes of package org.jpgolay.me.piece.list:
//            PieceListCRUD, PieceListAdvanceSearchGUI
public class PieceListController {

    public PieceListController(SearchBox pieceListSearch, TableViewer pieceListTable, JDesktopPane desktop) {
        this.pieceListSearch = null;
        this.pieceListTable = null;
        pieceListSearchGui = null;
        calendarPeriod = null;
        dateComboBox = null;
        this.pieceListSearch = pieceListSearch;
        this.pieceListTable = pieceListTable;
        this.desktop = desktop;
        date = new MEDate();
        crud = new PieceListCRUD();
        initSearch();
        initTable();
    }

    private void initSearch() {
        pieceListSearch.setList(new String[]{
                    "Code", "Raison social", "Numero", "Commercial (nom)", "Commercial (code)"
                });
        pieceListSearch.setVal("");
        pieceListSearch.setAdvanceSearch(getPieceListSearchGUI());
        pieceListSearch.getButtonRight().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionSearch();
            }
        });
        pieceListSearch.getTextField().addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                actionSearch();
            }
        });
    }

    private void initTable() {
        pieceListTable.setTypes(new Class[]{
                    java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.math.BigDecimal.class
                });
        pieceListTable.setLastColumnNotEditable(1);
        pieceListTable.setCellEditable(false);
        pieceListTable.setAlternateColor(MEUtility.PIECES_LINE);
        pieceListTable.setColumnNames(new String[]{
                    "NUMERO", "DATE", "DESTINATAIRE", "COMMERCIAL", "TTC"
                });
        pieceListTable.setPreferredColumnSize(new int[]{
                    40, 40, 50, 50, 30
                });
        actionSearch();
    }

    private PieceListAdvanceSearchGUI getPieceListSearchGUI() {
        if (pieceListSearchGui == null) {
            pieceListSearchGui = new PieceListAdvanceSearchGUI();
            pieceListSearchGui.setAgency(0);
            pieceListSearchGui.setPieceType(1);
            pieceListSearchGui.getButtonRight().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionCalendarPeriod();
                }
            });
        }
        return pieceListSearchGui;
    }

    private CalendarPeriod getCalendarPeriod() {
        if (calendarPeriod == null) {
            calendarPeriod = new CalendarPeriod();
            calendarPeriod.setFromDate("01/01/1991");
            calendarPeriod.setToDate("01/01/2090");
            calendarPeriod.getButtonLeft().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionCalendarPeriodOK();
                }
            });
            calendarPeriod.getButtonRight().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionCalendarPeriodCANCEL();
                }
            });
            calendarPeriod.setLocation(600, 50);
            calendarPeriod.setSize(320, 130);
        }
        return calendarPeriod;
    }

    private void actionSearch() {
        String from = getCalendarPeriod().getFromDate();
        String to = getCalendarPeriod().getToDate();
        int agency = getPieceListSearchGUI().getAgency() + 1;
        int piece = getPieceListSearchGUI().getPieceType();
        StringBuffer sql = new StringBuffer();
        if (pieceListSearch.getSelectedIndex() == 1) {
            if (piece == 3 || piece == 4) {
                sql.append("SELECT ventes_factures.id, date, raison_sociale, ventes_factures.commerciaux_id, net_a_payer FROM ventes_factures, clients ");
            } else if (piece == 5 || piece == 6) {
                sql.append("SELECT achats.id, date, raison_sociale, achats.commerciaux_id, net_a_payer FROM achats, fournisseurs ");
            } else {
                sql.append("SELECT ventes.id, date, raison_sociale, ventes.commerciaux_id, net_a_payer FROM ventes, clients ");
            }
        } else if (pieceListSearch.getSelectedIndex() == 3) {
            if (piece == 3 || piece == 4) {
                sql.append("SELECT ventes_factures.id, date, clients_id, nom, net_a_payer FROM ventes_factures, commerciaux ");
            } else if (piece == 5 || piece == 6) {
                sql.append("SELECT achats.id, date, fournisseurs_id, nom, net_a_payer FROM achats, commerciaux ");
            } else {
                sql.append("SELECT ventes.id, date, clients_id, nom, net_a_payer FROM ventes, commerciaux ");
            }
        } else if (piece == 3 || piece == 4) {
            sql.append("SELECT id, date, clients_id, commerciaux_id, net_a_payer FROM ventes_factures ");
        } else if (piece == 5 || piece == 6) {
            sql.append("SELECT id, date, fournisseurs_id, commerciaux_id, net_a_payer FROM achats ");
        } else {
            sql.append("SELECT id, date, clients_id, commerciaux_id, net_a_payer FROM ventes ");
        }
        switch (piece) {
            case 0: // '\0'
                sql.append("WHERE prefixe = 'D'");
                break;

            case 1: // '\001'
                sql.append("WHERE prefixe = 'C'");
                break;

            case 2: // '\002'
                sql.append("WHERE prefixe = 'BL'");
                break;

            case 3: // '\003'
                sql.append("WHERE prefixe = 'F'");
                break;

            case 4: // '\004'
                sql.append("WHERE prefixe = 'A'");
                break;

            case 5: // '\005'
                sql.append("WHERE prefixe = 'C'");
                break;

            case 6: // '\006'
                sql.append("WHERE prefixe = 'F'");
                break;
        }
        if (agency != 6) {
            sql.append(" AND entreprise_id=");
            sql.append(agency);
        }
        sql.append(" AND date BETWEEN '");
        sql.append(date.toMysql(from));
        sql.append("' AND '");
        sql.append(date.toMysql(to));
        switch (pieceListSearch.getSelectedIndex()) {
            case 0: // '\0'
                if (piece == 5 || piece == 6) {
                    if (pieceListSearch.getVal().equals("")) {
                        sql.append("' ORDER BY fournisseurs_id");
                    } else {
                        sql.append("' AND fournisseurs_id LIKE '");
                        sql.append(pieceListSearch.getVal());
                        sql.append("%' ORDER BY fournisseurs_id");
                    }
                    break;
                }
                if (pieceListSearch.getVal().equals("")) {
                    sql.append("' ORDER BY clients_id");
                } else {
                    sql.append("' AND clients_id LIKE '");
                    sql.append(pieceListSearch.getVal());
                    sql.append("%' ORDER BY clients_id");
                }
                break;

            case 1: // '\001'
                if (piece == 5 || piece == 6) {
                    if (pieceListSearch.getVal().equals("")) {
                        sql.append("' AND fournisseurs_id=fournisseurs.id");
                        sql.append(" ORDER BY raison_sociale");
                    } else {
                        sql.append("' AND fournisseurs_id=fournisseurs.id");
                        sql.append(" AND raison_sociale LIKE '");
                        sql.append(pieceListSearch.getVal());
                        sql.append("%' ORDER BY raison_sociale");
                    }
                    break;
                }
                if (pieceListSearch.getVal().equals("")) {
                    sql.append("' AND clients_id=clients.id");
                    sql.append(" ORDER BY raison_sociale");
                } else {
                    sql.append("' AND clients_id=clients.id");
                    sql.append(" AND raison_sociale LIKE '");
                    sql.append(pieceListSearch.getVal());
                    sql.append("%' ORDER BY raison_sociale");
                }
                break;

            case 2: // '\002'
                if (pieceListSearch.getVal().equals("")) {
                    sql.append("' ORDER BY id");
                } else {
                    sql.append("' AND id LIKE '");
                    sql.append(pieceListSearch.getVal());
                    sql.append("%' ORDER BY id");
                }
                break;

            case 3: // '\003'
                if (pieceListSearch.getVal().equals("")) {
                    sql.append("' AND commerciaux_id=commerciaux.id");
                    sql.append(" ORDER BY nom");
                } else {
                    sql.append("' AND commerciaux_id=commerciaux.id");
                    sql.append(" AND nom LIKE '");
                    sql.append(pieceListSearch.getVal());
                    sql.append("%' ORDER BY nom");
                }
                break;

            case 4: // '\004'
                if (pieceListSearch.getVal().equals("")) {
                    sql.append("' ORDER BY commerciaux_id");
                } else {
                    sql.append("' AND commerciaux_id LIKE '");
                    sql.append(pieceListSearch.getVal());
                    sql.append("%' ORDER BY commerciaux_id");
                }
                break;

            default:
                if (piece == 5 || piece == 6) {
                    if (pieceListSearch.getVal().equals("")) {
                        sql.append("' ORDER BY fournisseurs_id");
                    } else {
                        sql.append("' AND fournisseurs_id LIKE '");
                        sql.append(pieceListSearch.getVal());
                        sql.append("%' ORDER BY fournisseurs_id");
                    }
                    break;
                }
                if (pieceListSearch.getVal().equals("")) {
                    sql.append("' ORDER BY clients_id");
                } else {
                    sql.append("' AND clients_id LIKE '");
                    sql.append(pieceListSearch.getVal());
                    sql.append("%' ORDER BY clients_id");
                }
                break;
        }
        Object data[][] = crud.getDataList(sql.toString());
        if (data != null) {
            pieceListTable.setData(data);
        } else {
            pieceListTable.setData(getEmptyTable());
        }
    }

    private Object[][] getEmptyTable() {
        Object data[][] = new Object[3][5];
        for (int i = 0; i < data.length; i++) {
            data[i][0] = null;
            if (i == 1) {
                data[i][1] = "AUCUNE";
                data[i][2] = "PIECES";
            } else {
                data[i][1] = null;
                data[i][2] = null;
            }
            data[i][3] = null;
            data[i][4] = null;
        }

        return data;
    }

    private void actionCalendarPeriod() {
        getCalendarPeriod().setVisible(true);
        getCalendarPeriod().toFront();
        desktop.add(getCalendarPeriod(), JLayeredPane.DEFAULT_LAYER);
        try {
            getCalendarPeriod().setSelected(true);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    }

    private void actionCalendarPeriodOK() {
        getPieceListSearchGUI().setPeriode(getCalendarPeriod().getMessage());
        actionCalendarPeriodCANCEL();
    }

    private void actionCalendarPeriodCANCEL() {
        getCalendarPeriod().setVisible(false);
        desktop.remove(getCalendarPeriod());
    }

    public int getPieceType() {
        return pieceListSearchGui.getPieceType();
    }
    private SearchBox pieceListSearch;
    private TableViewer pieceListTable;
    private PieceListAdvanceSearchGUI pieceListSearchGui;
    private CalendarPeriod calendarPeriod;
    private PieceListCRUD crud;
    private JDesktopPane desktop;
    private DateComboBox dateComboBox;
    private MEDate date;
}
